﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SangsTools;
using System.Linq;

namespace Battle
{
    public class EnemyMgr : SingletonScript<EnemyMgr>,IEnemyTargetGetter
    {
        public event System.Action<ST_EnemyDeathInfo> EventOnEnemyDeath;

        public List<EnemyBase> AllEnemy { get; private set; } = new List<EnemyBase>();

        public EnemyBase[] GetEnemysInRange(Vector3 pos, float range)
        {
            float dis = range * range;
            return AllEnemy.FindAll((enemy) => (enemy.transform.position - pos).sqrMagnitude <= dis).ToArray();
        }

        public void LogIn(EnemyBase enemy)
        {
            if (enemy != null && !AllEnemy.Contains(enemy))
                AllEnemy.Add(enemy);
        }
        public void LogOut(EnemyBase enemy)
        {
            if (enemy != null && AllEnemy.Contains(enemy))
                AllEnemy.Remove(enemy);
        }

        public void OnEnemyDeath(EnemyBase enemy)
        {
            if (enemy == null || !AllEnemy.Contains(enemy)) return;
            AllEnemy.Remove(enemy);
            EventOnEnemyDeath?.Invoke(new ST_EnemyDeathInfo()
            {
                nGoldReward = enemy.GoldReward,
                nScienceReward = enemy.ScienceReward,
            });
        }

        public void Reset()
        {
            var arrTmp = AllEnemy.ToArray();
            AllEnemy.Clear();//情况列表，放置敌人删除触发事件

            for (int i = 0; i < arrTmp.Length; i++)
            {
                arrTmp[i].Death();
            }
        }

        public ICanHitObj GetTarget(Vector3 pos, ICanHitObj[] otherTargets = null)
        {
              //TODO 每次都排序吃效率，考虑优化
            List<EnemyBase> enemys;
            if (otherTargets == null)
                enemys = AllEnemy;
            else
                enemys = AllEnemy.FindAll((enemy) => !otherTargets.Contains(enemy));

            if (enemys.Count <= 0) 
                return null;
            else 
                return enemys.OrderBy((enemy) => (enemy.transform.position - pos).sqrMagnitude).First();
        }
    }

}